package com.nic.view.widget;

import android.media.MediaPlayer;

import java.io.IOException;

/**
 * Created by Administrator on 2018/5/17.
 */

public class AudioPlayer {
    private static AudioPlayer mAudioPlayer;

    public static AudioPlayer getInstance() {
        if (mAudioPlayer == null)
            mAudioPlayer = new AudioPlayer();
        return mAudioPlayer;
    }

    private MediaPlayer mPlayer;
    private boolean isPlaying = false;

    public void stop() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    public void play(String filePath) {
        if (mPlayer != null && mPlayer.isPlaying()) {
            return;
        }
        try {
            // 避免多次单击重复创建MediaPlayer实例
            stop();
            mPlayer = new MediaPlayer();
            mPlayer.setDataSource(filePath);
            mPlayer.prepare();
            //        MediaPlayer.create(App.getInstance().getApplicationContext(), Uri.fromFile(new File(filePath)));
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    isPlaying = false;
                    stop();
                    if (mOnCompleteListener != null) {
                        mOnCompleteListener.onComplete();
                    }
                }
            });
            mPlayer.start();
            isPlaying = true;
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    public boolean isPlaying() {
        return isPlaying;
    }

    private OnCompleteListener mOnCompleteListener;

    public void setOnCompleteListener(OnCompleteListener mOnCompleteListener) {
        this.mOnCompleteListener = mOnCompleteListener;
    }

    public interface OnCompleteListener {
        void onComplete();
    }
}
